module API::V2
  class Traffics < Grape::API
    resource :traffics do
      post do
        terminal = Terminal.where(mac: params[:mac]).first_or_create
        if terminal and  params[:traffic]
          traffic = Traffic.new params[:traffic]
          traffic.flow = traffic_flow_from_params(params[:traffic][:flow])
          traffic.device = terminal
          traffic.save!
        else
          not_found!
        end
      end

      desc "Return traffics used by the terminal and the current limit"
      get ':mac' do
        # max traffic read from settings.yml
        max_traffic = traffic_flow_from_params(Settings.max_traffic)

        # terminal current traffic equals to zero once not exists
        terminal = Terminal.where(mac: params[:mac]).first
        current_traffic = traffic_flow_from_params(terminal ? terminal.current_traffic : 0)

        # send the response
        {current_traffic: current_traffic, 
          traffic_used: (current_traffic.to_f / max_traffic).round(5), 
          is_avaiable: (current_traffic < max_traffic)}
      end
    end
  end
end